package com.imti.xmldemo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class XMLUtil
{

    public static List<Person> parsePersonListByPull(InputStream is)
        throws XmlPullParserException, IOException
    {
        //获取Pull解析器
        XmlPullParser parser =
            XmlPullParserFactory.newInstance().newPullParser();

        List<Person> personList = null;
        Person person = null;

        parser.setInput(is, "UTF-8");

        //首次获取时eventType始终为XmlPullParser.START_DOCUMENT
        int eventType = parser.getEventType();

        //文档结束时结束循环
        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            switch (eventType)
            {
                //文档开始时创建列表
                case XmlPullParser.START_DOCUMENT:
                    personList = new ArrayList<>();
                    break;
                //标签开始
                case XmlPullParser.START_TAG:
                    //获取标签名
                    switch (parser.getName())
                    {
                        case "person":
                            person = new Person();
                            //PULL解析获取属性时，会按照xml顺序获取属性
                            //与SAX通过属性名称获取属性不同
                            person.setId(parser.getAttributeValue(0));
                            //<person id="11">
                            //<person android:id="11">
//                            person.setId(parser.getAttributeValue("", "id"));
                            break;

                        case "name":
                            if (null != person)
                            {
                                person.setName(parser.nextText());
                            }
                            break;

                        case "age":
                            if (null != person)
                            {
                                person.setAge(parser.nextText());
                            }
                            break;
                    }
                    break;

                case XmlPullParser.END_TAG:
                    if ("person".equals(parser.getName()))
                    {
                        personList.add(person);
                        person = null;
                    }
                    break;
            }

            //轮动解析，如果while循环最后没有修改eventType，则会死循环
            eventType = parser.next();
        }

        return personList;
    }
}
